<!DOCTYPE html>
<html lang="en">
  <head>
    <title>
        Java-framework-Spring-4 - rulerLwx Blog
      </title>
        <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-transform" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no,email=no,adress=no">
    
    <meta name="theme-color" content="#000000" />
    
    <meta http-equiv="window-target" content="_top" />
    
    
    <meta name="description" content="后处理器 允许通过两个后处理器对IoC容器进行扩展。常用的后处理器有两种： Bean后处理器，对容器中的Bean进行后处理，对Bean进行额外加" />
    <meta name="generator" content="Hugo 0.73.0 with theme pure" />
    <title>Java-framework-Spring-4 - rulerLwx Blog</title>
    
    
    <link rel="stylesheet" href="https://rulerLwx.gitee.io/css/style.min.c4bc7071f132c964c2116bca53b392933f377e5ca7b7051ed245187c621a2d3e.css">
    
    <link rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/9.15.10/styles/github.min.css" async>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.css" async>
    <meta property="og:title" content="Java-framework-Spring-4" />
<meta property="og:description" content="后处理器 允许通过两个后处理器对IoC容器进行扩展。常用的后处理器有两种： Bean后处理器，对容器中的Bean进行后处理，对Bean进行额外加" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://rulerLwx.gitee.io/2019/08/java-framework-spring-4/" />
<meta property="article:published_time" content="2019-08-15T11:06:30+08:00" />
<meta property="article:modified_time" content="2019-08-15T11:06:30+08:00" />
<meta itemprop="name" content="Java-framework-Spring-4">
<meta itemprop="description" content="后处理器 允许通过两个后处理器对IoC容器进行扩展。常用的后处理器有两种： Bean后处理器，对容器中的Bean进行后处理，对Bean进行额外加">
<meta itemprop="datePublished" content="2019-08-15T11:06:30&#43;08:00" />
<meta itemprop="dateModified" content="2019-08-15T11:06:30&#43;08:00" />
<meta itemprop="wordCount" content="4408">



<meta itemprop="keywords" content="" /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="Java-framework-Spring-4"/>
<meta name="twitter:description" content="后处理器 允许通过两个后处理器对IoC容器进行扩展。常用的后处理器有两种： Bean后处理器，对容器中的Bean进行后处理，对Bean进行额外加"/>

    <!--[if lte IE 9]>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
      <![endif]-->

    <!--[if lt IE 9]>
        <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
      <![endif]-->
  </head>

  
  

  <body class="main-center theme-black" itemscope itemtype="http://schema.org/WebPage"><header class="header" itemscope itemtype="http://schema.org/WPHeader">
    <div class="slimContent">
      <div class="navbar-header">
        <div class="profile-block text-center">
          <a id="avatar" href="https://gitee.com/rulerLwx" target="_blank">
            <img class="img-circle img-rotate" src="https://rulerLwx.gitee.io/avatar.png" width="200" height="200">
          </a>
          <h2 id="name" class="hidden-xs hidden-sm">rulerLwx</h2>
          <h3 id="title" class="hidden-xs hidden-sm hidden-md">thinking...</h3>
          <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i>Guangzhou, China</small>
        </div><div class="search" id="search-form-wrap">
    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="Search" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i
                        class="icon icon-search"></i></button>
            </span>
        </div>
        <div class="ins-search">
            <div class="ins-search-mask"></div>
            <div class="ins-search-container">
                <div class="ins-input-wrapper">
                    <input type="text" class="ins-search-input" placeholder="Type something..."
                        x-webkit-speech />
                    <button type="button" class="close ins-close ins-selectable" data-dismiss="modal"
                        aria-label="Close"><span aria-hidden="true">×</span></button>
                </div>
                <div class="ins-section-wrapper">
                    <div class="ins-section-container"></div>
                </div>
            </div>
        </div>
    </form>
</div>
        <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
      </div>
      <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
        <ul class="nav navbar-nav main-nav">
            <li class="menu-item menu-item-home">
                <a href="/">
                    <i class="icon icon-home-fill"></i>
                  <span class="menu-title">Home</span>
                </a>
            </li>
            <li class="menu-item menu-item-archives">
                <a href="/posts/">
                    <i class="icon icon-archives-fill"></i>
                  <span class="menu-title">Archives</span>
                </a>
            </li>
            <li class="menu-item menu-item-categories">
                <a href="/categories/">
                    <i class="icon icon-folder"></i>
                  <span class="menu-title">Categories</span>
                </a>
            </li>
            <li class="menu-item menu-item-tags">
                <a href="/tags/">
                    <i class="icon icon-tags"></i>
                  <span class="menu-title">Tags</span>
                </a>
            </li>
            <li class="menu-item menu-item-about">
                <a href="/about/">
                    <i class="icon icon-cup-fill"></i>
                  <span class="menu-title">About</span>
                </a>
            </li>
        </ul>
      </nav>
    </div>
  </header>

<aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title">Board</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">enjoy~
            </div>
        </div>
    </div>
</div>

      <div class="widget">
    <h3 class="widget-title"> Categories</h3>
    <div class="widget-body">
        <ul class="category-list">
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-framework/" class="category-list-link">java-framework</a><span class="category-list-count">38</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-front-end/" class="category-list-link">java-front-end</a><span class="category-list-count">11</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-se/" class="category-list-link">java-se</a><span class="category-list-count">21</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-senior/" class="category-list-link">java-senior</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/linux/" class="category-list-link">linux</a><span class="category-list-count">13</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/tools/" class="category-list-link">tools</a><span class="category-list-count">1</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%8A%80%E6%9C%AF%E6%9D%82%E7%83%A9/" class="category-list-link">技术杂烩</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" class="category-list-link">数据库</a><span class="category-list-count">15</span></li>
        </ul>
    </div>
</div>
      <div class="widget">
    <h3 class="widget-title"> Tags</h3>
    <div class="widget-body">
        <ul class="tag-list">
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/jvm/" class="tag-list-link">jvm</a><span
                    class="tag-list-count">1</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" class="tag-list-link">多线程</a><span
                    class="tag-list-count">2</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" class="tag-list-link">网络编程</a><span
                    class="tag-list-count">3</span></li>
            
        </ul>

    </div>
</div>
      
<div class="widget">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget-body">
        <ul class="recent-post-list list-unstyled no-thumbnail">
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%87%AA%E5%B7%B1%E5%8A%A8%E6%89%8B%E4%B8%80%E6%89%B9%E9%87%8F%E7%A7%BB%E5%8A%A8%E9%87%8D%E5%91%BD%E5%90%8D%E6%96%87%E4%BB%B6/" class="title">自己动手（一）——批量移动、重命名文件</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-27 17:50:02 &#43;0800 CST" itemprop="datePublished">2020-07-27</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E5%85%B3%E4%BA%8Einteger%E7%9A%84-128~127%E7%BC%93%E5%AD%98/" class="title">关于Integer的 -128~127缓存</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-11 16:56:21 &#43;0800 CST" itemprop="datePublished">2020-07-11</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98/" class="title">跨域问题</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-08 22:41:12 &#43;0800 CST" itemprop="datePublished">2020-07-08</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E4%B8%AA%E4%BA%BA%E5%8D%9A%E5%AE%A2%E6%90%AD%E5%BB%BA/" class="title">个人博客搭建</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-05 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-05</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/mongodb-1/" class="title">MonggoDB-1</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-03 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-03</time>
                    </p>
                </div>
            </li>
        </ul>
    </div>
</div>
  </div>
</aside>

    
    
<aside class="sidebar sidebar-toc collapse" id="collapseToc" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    <h4 class="toc-title">Catalogue</h4>
    <nav id="toc" class="js-toc toc">

    </nav>
  </div>
</aside>
<main class="main" role="main"><div class="content">
  <article id="-" class="article article-type-" itemscope
    itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      <h1 itemprop="name">
  <a
    class="article-title"
    href="/2019/08/java-framework-spring-4/"
    >Java-framework-Spring-4</a
  >
</h1>

      <div class="article-meta">
        
<span class="article-date">
  <i class="icon icon-calendar-check"></i>&nbsp;
<a href="https://rulerLwx.gitee.io/2019/08/java-framework-spring-4/" class="article-date">
  <time datetime="2019-08-15 11:06:30 &#43;0800 CST" itemprop="datePublished">2019-08-15</time>
</a>
</span>
<span class="article-category">
  <i class="icon icon-folder"></i>&nbsp;
  <a class="article-category-link" href="/categories/java-framework/"> Java-framework </a>
</span>

        <span class="post-comment"><i class="icon icon-comment"></i>&nbsp;<a href="/2019/08/java-framework-spring-4/#comments"
            class="article-comment-link">Comments</a></span>
		<span class="post-wordcount hidden-xs" itemprop="wordCount">Word Count: 4408words</span>
		<span class="post-readcount hidden-xs" itemprop="timeRequired">Read Count: 9minutes </span>
      </div>
    </div>
    <div class="article-entry marked-body js-toc-content" itemprop="articleBody">
      <h1 id="后处理器">后处理器</h1>
<p>允许通过两个后处理器对IoC容器进行扩展。常用的后处理器有两种：</p>
<ul>
<li>Bean后处理器，对容器中的Bean进行后处理，对Bean进行额外加强。</li>
<li>容器后处理器，对IoC容器进行后处理，增加容器功能。</li>
</ul>
<h2 id="bean后处理器">Bean后处理器</h2>
<p>实现BeanPostProcessor接口，BeanPostProcessor接口有两个方法：</p>
<ul>
<li>Object postProcessBeforeInitialization(Object bean, String beanName)，bean初始化之前被回调。</li>
<li>Object postProcessAfterInitialization(Object bean, String beanName)，bean初始化之后被回调。</li>
</ul>
<p>这两个方法，第一参数是系统即将进行后处理的bean实例，第二个参数是该bean的id。</p>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img/20200708091535.png" alt=""></p>
<p>上图是Bean后处理器两个方法的回调时机</p>
<p>BeanPostProcessor通常用来检查标记接口，或做如将Bean包装成一个Proxy的事情。</p>
<p>示例：</p>
<pre><code>public class MyBeanPostProcessor implements BeanPostProcessor
{
	/**
	 * 对容器中的Bean实例进行后处理
	 * @param bean 需要进行后处理的原Bean实例
	 * @param beanName 需要进行后处理的Bean的配置id
	 * @return 返回后处理完成后的Bean
	 */
	public Object postProcessBeforeInitialization (Object bean , String beanName){
		System.out.println(&quot;Bean后处理器在初始化之前对&quot;+ beanName + &quot;进行增强处理...&quot;);
		// 返回的处理后的Bean实例，该实例就是容器中实际使用的Bean
		// 该Bean实例甚至可与原Bean截然不同
		return bean;
	}
	
	public Object postProcessAfterInitialization (Object bean , String beanName){
		System.out.println(&quot;Bean后处理器在初始化之后对&quot;+ beanName + &quot;进行增强处理...&quot;);
		// 如果该Bean是Chinese类的实例
		if (bean instanceof Chinese)	{
			// 修改其name成员变量
			Chinese c = (Chinese)bean;
			c.setName(&quot;疯狂iOS讲义&quot;);
		}
		return bean;
	}
}
</code></pre>
<pre><code>public class Chinese implements Person,InitializingBean{
	private Axe axe;
	private String name;
	public Chinese(){
		System.out.println(&quot;Spring实例化主调bean：Chinese实例...&quot;);
	}
	public void setAxe(Axe axe){
		this.axe = axe;
	}
	public void setName(String name){
		System.out.println(&quot;Spring执行setName()方法注入依赖关系...&quot;);
		this.name = name;
	}
	public void useAxe(){
		System.out.println(name + axe.chop());
	}
	
	// 下面是两个生命周期方法
	public void init(){
		System.out.println(&quot;正在执行初始化方法 init...&quot;);
	}
	public void afterPropertiesSet() throws Exception{
		System.out.println(&quot;正在执行初始化方法 afterPropertiesSet...&quot;);
	}
}
</code></pre>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;GBK&quot;?&gt;
&lt;beans xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xmlns=&quot;http://www.springframework.org/schema/beans&quot;
	xmlns:p=&quot;http://www.springframework.org/schema/p&quot;
	xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd&quot;&gt;

	&lt;bean id=&quot;steelAxe&quot; class=&quot;org.crazyit.app.service.impl.SteelAxe&quot;/&gt;
	&lt;bean id=&quot;chinese&quot; class=&quot;org.crazyit.app.service.impl.Chinese&quot; init-method=&quot;init&quot; p:axe-ref=&quot;steelAxe&quot; p:name=&quot;依赖注入的值&quot;/&gt;

	&lt;bean id=&quot;bp&quot; class=&quot;org.crazyit.app.util.MyBeanPostProcessor&quot;/&gt;
&lt;/beans&gt;
</code></pre>
<pre><code>public class BeanTest{
	public static void main(String[] args)throws Exception{
		// 以类加载路径下的beans.xml文件来创建Spring容器
//		ApplicationContext ctx = new ClassPathXmlApplicationContext(&quot;beans.xml&quot;);
//		Person p = (Person)ctx.getBean(&quot;chinese&quot;);

		Resource isr = new ClassPathResource(&quot;beans.xml&quot;);
		DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
		// 让默认的BeanFactory容器加载isr对应的XML配置文件
		new XmlBeanDefinitionReader(beanFactory).loadBeanDefinitions(isr);
		// 获取容器中的Bean后处理器
		BeanPostProcessor bp = (BeanPostProcessor)beanFactory.getBean(&quot;bp&quot;);
		// 注册Bean后处理器
		beanFactory.addBeanPostProcessor(bp);
		Person p = (Person)beanFactory.getBean(&quot;chinese&quot;);
		p.useAxe();
	}
}
</code></pre>
<h2 id="容器后处理器">容器后处理器</h2>
<p>实现BeanFactoryPostProcessor接口，该接口有如下方法：</p>
<p>void postProcessBeanFactory( ConfigurableListableBeanFactory beanFactory)，通过此方法可以对容器进行自定义扩展。</p>
<p>Spring提供的其它几个常用的后处理器：</p>
<ul>
<li>PropertyPlaceholderConfigurer：属性点位符配置器。</li>
<li>PropertyOverrideConfigurer：重写占位符配置器。</li>
<li>CustomAutowireConfigurer：自定义自动装配的配置器。</li>
<li>CustomScopeConfigurer：自定义作用域的配置器。</li>
</ul>
<p>主要用于配置用的？？？？</p>
<h3 id="属性占位符配置器">属性占位符配置器</h3>
<p>PropertyPlaceholderConfigurer：属性占位符配置器。</p>
<p>负责读取Properties属性文件里的属性值，并将这些属性值设置成spring配置文件中数据。</p>
<pre><code>jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring
jdbc.username=root
jdbc.password=32147
</code></pre>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;GBK&quot;?&gt;
&lt;beans xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xmlns=&quot;http://www.springframework.org/schema/beans&quot;
	xmlns:p=&quot;http://www.springframework.org/schema/p&quot;
	xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd&quot;&gt;

	&lt;bean class=&quot;org.springframework.beans.factory.config.PropertyPlaceholderConfigurer&quot;&gt;
		&lt;property name=&quot;locations&quot;&gt;
			&lt;list&gt;
				&lt;value&gt;dbconn.properties&lt;/value&gt;
				&lt;!-- 如果有多个属性文件,依次在下面列出来 --&gt;
				&lt;!--value&gt;wawa.properties&lt;/value--&gt;
			&lt;/list&gt;
		&lt;/property&gt;
	&lt;/bean&gt;

	&lt;bean id=&quot;dataSource&quot; class=&quot;com.mchange.v2.c3p0.ComboPooledDataSource&quot;
		destroy-method=&quot;close&quot;
		p:driverClass=&quot;${jdbc.driverClassName}&quot;
		p:jdbcUrl=&quot;${jdbc.url}&quot;
		p:user=&quot;${jdbc.username}&quot;
		p:password=&quot;${jdbc.password}&quot;/&gt;
&lt;/beans&gt;
</code></pre>
<p>如果引入了context:命名空间，则可采用如下方式来配置属性占位符：</p>
<p>&lt;context:property-placeholder location=&quot;classpath:config.properties&rdquo; /&gt;</p>
<p><a href="context:property-placeholder.../">context:property-placeholder.../</a>元素是PropertyPlaceholderConfigurer的简化配置。</p>
<h3 id="重写占位符配置器">重写占位符配置器</h3>
<p>PropertyOverrideConfigurer：重写占位符配置器。</p>
<p>PropertyOverrideConfigurer的功能比上面PropertyPlaceholderConfigurer的功能更加强大：PropertyOverrideConfigurer的属性文件的信息可以覆盖Spring配置文件中的无数据。</p>
<p>PropertyPlaceholderConfigurer的属性文件，每条属性格式如下：beanId.property=value</p>
<pre><code>dataSource.driverClass=com.mysql.jdbc.Driver
dataSource.jdbcUrl=jdbc:mysql://localhost:3306/spring
dataSource.user=root
dataSource.password=32147
</code></pre>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;GBK&quot;?&gt;
&lt;beans xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xmlns=&quot;http://www.springframework.org/schema/beans&quot;
	xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd&quot;&gt;

	&lt;bean class=&quot;org.springframework.beans.factory.config.PropertyOverrideConfigurer&quot;&gt;
		&lt;property name=&quot;locations&quot;&gt;
			&lt;list&gt;
				&lt;value&gt;dbconn.properties&lt;/value&gt;
				&lt;!-- 如果有多个属性文件,依次在下面列出来 --&gt;
			&lt;/list&gt;
		&lt;/property&gt;
	&lt;/bean&gt;
	&lt;!-- 定义数据源Bean，使用C3P0数据源实现,配置该Bean时没有指定任何信息，但Properties文件里的信息将会直接覆盖该Bean的属性值 --&gt;
	&lt;bean id=&quot;dataSource&quot; class=&quot;com.mchange.v2.c3p0.ComboPooledDataSource&quot; destroy-method=&quot;close&quot;/&gt;
&lt;/beans&gt;
</code></pre>
<p>如果引入了context:命名空间，则可采用如下方式来配置属性占位符：</p>
<p>&lt;context:property-override location=&quot;classpath:config.properties&rdquo; /&gt;</p>
<p><a href="context:property-override.../">context:property-override.../</a>元素是PropertyOverrideConfigurer的简化配置。</p>
<h1 id="零配置支持">“零配置”支持</h1>
<p>“零配置”，指用Annotation代替xml的配置。</p>
<h2 id="搜索bean">搜索Bean</h2>
<p>Spring提供如下几个Annotation来标注Bean：</p>
<ul>
<li>@Component：标注一个普通的Bean。</li>
<li>@Controller：标注一个控制器组件类。</li>
<li>@Service：标注一个业务逻辑组件类。</li>
<li>@Repository：标注一个DAO组件类。</li>
</ul>
<p>自动扫描的配置：</p>
<p>1、引入context:命名空间</p>
<pre><code>xmlns:context=&quot;http://www.springframework.org/schema/context
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
</code></pre>
<p>2、配置自动扫描的包路径</p>
<pre><code>&lt;context:component-scan base-package=&quot;org.crazyit.app.service&quot;/&gt;
</code></pre>
<p>可以通过为<a href="context:component-scan.../">context:component-scan.../</a>元素添加&lt;include-filter&hellip;/&gt;或&lt;exclude-filter&hellip;/&gt;子元素来指定是否加载或不加载某些元素。</p>
<p>&lt;include-filter&hellip;/&gt;或&lt;exclude-filter&hellip;/&gt;可以指定以下两个属性：</p>
<ul>
<li>type：指定过滤器类型。</li>
<li>expression：指定过滤器所需要的表达式。</li>
</ul>
<p>其中type可以指定如下四种过滤器：</p>
<ul>
<li>annotation：Annotation过滤器，指定一个用Annotation名，如&lt;context:exclude-filter type=&quot;annotation&rdquo; expression=&quot;org.springframework.stereotype.Controller&rdquo;/&gt;</li>
<li>assignable：类名过滤器，指定一个java类。</li>
<li>regex：正式表达式过滤器，指定一个正则表达式，如org.example.Default.*。</li>
<li>aspectj：AspectJ过滤器，如org.example..*Service+。</li>
</ul>
<p>示例：</p>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;GBK&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
	xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-4.0.xsd&quot;&gt;

	&lt;context:component-scan base-package=&quot;org.crazyit.app.service&quot;&gt;
		&lt;!-- 只将以Chinese、Axe结尾的类当成Spring容器中的Bean --&gt;
		&lt;context:include-filter type=&quot;regex&quot; expression=&quot;.*Chinese&quot;/&gt;
		&lt;context:include-filter type=&quot;regex&quot; expression=&quot;.*Axe&quot;/&gt;
	&lt;/context:component-scan&gt;
&lt;/beans&gt;
</code></pre>
<h2 id="configuration-和-bean">@Configuration 和 @Bean</h2>
<p>Spring的Java配置方式是通过 @Configuration 和 @Bean 这两个注解实现的：</p>
<p>1、@Configuration 作用于类上，相当于一个xml配置文件；</p>
<p>2、@Bean 作用于方法上，相当于xml配置中的<!-- raw HTML omitted -->；</p>
<pre><code>@Configuration //通过该注解来表明该类是一个Spring的配置，相当于一个xml文件
@ComponentScan(basePackages = &quot;cn.itcast.springboot.javaconfig&quot;) //配置扫描包
public class SpringConfig {
    
    @Bean // 通过该注解来表明是一个Bean对象，相当于xml中的&lt;bean&gt;
    public UserDAO getUserDAO(){
        return new UserDAO(); // 直接new对象做演示
    }
    
}
</code></pre>
<h2 id="bean作用域">Bean作用域</h2>
<p>@Scope(“prototype”)，在引号中提供bean的作用域名称即可。</p>
<p>Bean的作用域：singleton、prototype、request、session、global session。默认是singleton。</p>
<h2 id="bean生命周期">Bean生命周期</h2>
<p>@PostConstruct、@PreDestroy用于修饰方法，分别对应init-method、destory-method。</p>
<h2 id="resource配置依赖">@Resource配置依赖</h2>
<p>@Resource有一个name属性，在默认情况下，Spring将这个值解释为需要被注入的Bean实例的id，与&lt;property &hellip;/&gt;元素的ref属性相同。</p>
<p>@Resource不仅可以修饰setter方法，也可以直接修饰实例变量。修饰实例变量时，可以连setter方法都可以不要。</p>
<p>@Resource可以省掉name属性，分两种情况：</p>
<p>1、修饰setter方法时，name属性默认为该setter方法去掉前面的set子串、首字母小写后得到的子串。如setName方法，子串为name。</p>
<p>2、修饰实例变量字段时，name属性默认与实例变量同名。</p>
<h2 id="propertysource-读取外部的资源配置文件">@PropertySource 读取外部的资源配置文件</h2>
<p>通过@PropertySource可以指定读取的配置文件，通过@Value注解获取值，具体用法：</p>
<pre><code>@Configuration //通过该注解来表明该类是一个Spring的配置，相当于一个xml文件
@ComponentScan(basePackages = &quot;cn.itcast.springboot.javaconfig&quot;) //配置扫描包
@PropertySource(value= {&quot;classpath:jdbc.properties&quot;})
public class SpringConfig {
    
    @Value(&quot;${jdbc.url}&quot;)
    private String jdbcUrl;
    
    @Bean // 通过该注解来表明是一个Bean对象，相当于xml中的&lt;bean&gt;
    public UserDAO getUserDAO(){
        return new UserDAO(); // 直接new对象做演示
    }
    
}
</code></pre>
<h2 id="importresource">@ImportResource</h2>
<p>Spring提供@ImportResource来加载xml配置</p>
<pre><code>@ImportResource({&quot;classpath:some-context.xml&quot;,&quot;classpath:another-context.xml&quot;})
</code></pre>
<h2 id="其它注解">其它注解</h2>
<ul>
<li>@DependsOn，强制初始化其它Bean，如@DependsOn({&ldquo;steelAxe&rdquo;,&ldquo;abc&rdquo;})。</li>
<li>@Lazy，是否取消预初始化，如@Lazy(true)。</li>
<li>@Autowired，自动装配，可以修饰setter方法、普通方法、实例变量和构造器等。可以根据泛型来装配，可以装配数组、集合。默认按byType装配，可以一起使用@Qualifier(&ldquo;id&rdquo;)指定id进行装配（还不如使用@Resource呢）。（注：@Autowired功能很强大）</li>
</ul>
<h2 id="resource与autowired的区别">@Resource与@Autowired的区别</h2>
<p>1、@Autowired与@Resource都可以用来装配bean.</p>
<p>都可以写在字段上,或写在setter方法上。其中@Autowired还可以修饰构造器、普通方法、实例变量和构造器等。可以根据泛型来装配，可以装配数组、集合。</p>
<p>2、@Autowired按byType自动注入（若想byName，则结合@Qualifier(&ldquo;id&rdquo;)），而@Resource默认按 byName自动注入。</p>
<p>3、@Resource有两个属性是比较重要的，分是name和type，Spring将@Resource注解的name属性解析为bean的名字，而type属性则解析为bean的类型。所以如果使用name属性，则使用byName的自动注入策略，而使用type属性时则使用byType自动注入策略。如果既不指定name也不指定type属性，这时将通过反射机制使用byName自动注入策略。？？</p>
<p>@Resource默认按名称装配，当找不到与名称匹配的bean才会按类型装配。</p>

    </div>
    <div class="article-footer">
<blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    <li class="post-copyright-link hidden-xs">
      <strong>Permalink: </strong>
      <a href="https://rulerLwx.gitee.io/2019/08/java-framework-spring-4/" title="Java-framework-Spring-4" target="_blank" rel="external">https://rulerLwx.gitee.io/2019/08/java-framework-spring-4/</a>
    </li>
    <li class="post-copyright-license">
      <strong>License：</strong><a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN</a>
    </li>
  </ul>
</blockquote>

<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://gitee.com/rulerLwx" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="https://rulerLwx.gitee.io/avatar.png" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://gitee.com/rulerLwx" target="_blank"><span class="text-dark">rulerLwx</span><small class="ml-1x">thinking...</small></a></h3>
        <div>Good Good Study, Day Day Up~</div>
      </div>
    </figure>
  </div>
</div>
    </div>
  </article>
<section id="comments">
    <div id="vcomments"></div>
</section>

</div><nav class="bar bar-footer clearfix" data-stick-bottom>
    <div class="bar-inner">
        <ul class="pager pull-left">
            <li class="prev">
                <a href="https://rulerLwx.gitee.io/2019/08/java-framework-spring-3-%E5%AE%B9%E5%99%A8/" title="Java-framework-Spring-3-容器"><i
                        class="icon icon-angle-left"
                        aria-hidden="true"></i><span>&nbsp;&nbsp;Older</span></a>
            </li>
            <li class="next">
                <a href="https://rulerLwx.gitee.io/2019/08/java-framework-spring-5-%E8%AE%BF%E9%97%AE%E8%B5%84%E6%BA%90/"
                    title="Java-framework-Spring-5-访问资源"><span>Newer&nbsp;&nbsp;</span><i
                        class="icon icon-angle-right" aria-hidden="true"></i></a>
            </li>
            
            <li class="toggle-toc">
                <a class="toggle-btn collapsed" data-toggle="collapse" href="#collapseToc" aria-expanded="false"
                    title="Catalogue" role="button">
                    <span>[&nbsp;</span><span>Catalogue</span>
                    <i class="text-collapsed icon icon-anchor"></i>
                    <i class="text-in icon icon-close"></i>
                    <span>]</span>
                </a>
            </li>
        </ul>
        <div class="bar-right">
            <div class="share-component" data-sites="weibo,qq,wechat"
                data-mobile-sites="weibo,qq,qzone"></div>
        </div>
    </div>
</nav>

</main><footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
<ul class="social-links">
    <li><a href="https://gitee.com/rulerLwx" target="_blank" title="gitee" data-toggle=tooltip data-placement=top >
            <i class="icon icon-gitee"></i></a></li>
    <li><a href="https://github.com/wolf-lea" target="_blank" title="github" data-toggle=tooltip data-placement=top >
            <i class="icon icon-github"></i></a></li>
</ul>
  <div class="copyright">
    &copy;2017  -
    2020
    <div class="publishby">
        Theme by <a href="https://github.com/xiaoheiAh" target="_blank"> xiaoheiAh </a>base on<a href="https://github.com/xiaoheiAh/hugo-theme-pure" target="_blank"> pure</a>.
    </div>
  </div>
</footer>

<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-MML-AM_SVG"></script>
<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
            showMathMenu: false, //disables context menu
            tex2jax: {
            inlineMath: [ ['$','$'], ['\\(','\\)'] ]
           }
    });
</script>


<script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script>
<script>
    window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/highlight.min.js"></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/python.min.js" defer></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/javascript.min.js" defer></script><script>
    hljs.configure({
        tabReplace: '    ', 
        classPrefix: ''     
        
    })
    hljs.initHighlightingOnLoad();
</script>
<script src="https://rulerLwx.gitee.io/js/application.min.bdeb64b910570b6c41badc6a05b7afb0c8ad9efd8525de3c7257d59e786326a3.js"></script>
<script src="https://rulerLwx.gitee.io/js/plugin.min.51ff8c7317566f82259170fa36e09c4493adc9b9378b427a01ad3f017ebac7dd.js"></script>

<script>
    (function (window) {
        var INSIGHT_CONFIG = {
            TRANSLATION: {
                POSTS: 'Posts',
                PAGES: 'Pages',
                CATEGORIES: 'Categories',
                TAGS: 'Tags',
                UNTITLED: '(Untitled)',
            },
            ROOT_URL: 'https:\/\/rulerLwx.gitee.io',
            CONTENT_URL: 'https:\/\/rulerLwx.gitee.io\/searchindex.json ',
        };
        window.INSIGHT_CONFIG = INSIGHT_CONFIG;
    })(window);
</script>
<script type="text/javascript" src="https://rulerLwx.gitee.io/js/insight.min.a343cd9a5a7698336b28ef3a7c16a3a1b1d2d5fb17dc8ed04022bbe08cc5459073a15bdafa3a8a58cdd56080784bdd69fa70b1ae8597565c799c57ed00f0e120.js" defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.min.js"></script>
<script>
    tocbot.init({
        
        tocSelector: '.js-toc',
        
        contentSelector: '.js-toc-content',
        
        headingSelector: 'h1, h2, h3',
        
        hasInnerContainers: true,
    });
</script>

<script src="https://cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine"></script>
<script type="text/javascript">
    var GUEST = ['nick', 'mail', 'link'];
    var meta = 'nick,mail';
    meta = meta.split(',').filter(function (item) {
        return GUEST.indexOf(item) > -1;
    });
    new Valine({
        el: '#vcomments',
        verify: null ,
        notify: null ,
        appId: 'IyAB0PSPRazTPDxitO1ddQ7O-gzGzoHsz',
        appKey: '5rBJTq4KidYF33eXwvRVhtEH',
        placeholder: 'enjoy~',
        avatar: 'mm',
        meta: meta,
        pageSize: '10' || 10,
        visitor: false 
});
</script>

  </body>
</html>
